package com.example.demonstrate.wang.test;

/**
 * @Author along
 * @Date 2024/6/7 15:44
 * @Description deadlock demo
 */
public class DeadlockExample {
    public static class ThreadA implements Runnable {
        private final Object lock1;
        private final Object lock2;

        public ThreadA(Object lock1, Object lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }

        @Override
        public void run() {
            synchronized (lock1) {
                System.out.println("ThreadA got lock1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                   e.printStackTrace();
               }
                synchronized (lock2) {
                    System.out.println("ThreadA got lock2");
                }
           }
       }
   }

   public static class ThreadB implements Runnable {
       private final Object lock1;
       private final Object lock2;

       public ThreadB(Object lock1, Object lock2) {
           this.lock1 = lock1;
           this.lock2 = lock2;
       }

       @Override
       public void run() {
           synchronized (lock2) {
               System.out.println("ThreadB got lock2");
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               synchronized (lock1) {
                   System.out.println("ThreadB got lock1");
               }
           }
       }
   }

    public static void main(String[] args) {

        Object lock1 = new Object();
        Object lock2 = new Object();
        Thread threadA = new Thread(new ThreadA(lock1, lock2));
        Thread threadB = new Thread(new ThreadB(lock1, lock2));
        threadA.start();
        threadB.start();
    }
}
